package com.ly.imgtooss.controller;

import com.ly.imgtooss.utils.UploadUtil;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 上传图片控制器
 */
@RestController
public class UploadController {

    @PostMapping("/upload")
    public String upload(MultipartFile file){
        // 1.file校验
        if (file.isEmpty()){
            return "图片上传失败!";
        }
        // 2.重命名图片 (a: 1.png    b: 1.bng)
        // 2.1 获取文件名
        String originalFilename = file.getOriginalFilename();
        // 2.2 获取后缀名
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 2.3 获取随机uuid,并去除uuid中的‘-’
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 2.4 拼接新的文件名
        String fileName = uuid + extName;
        // 3.上传图片
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        // 选择上传到本地的地址
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()
                + "\\src\\main\\resources\\static\\images\\";
        String path = pre + fileName;
        try {
            file.transferTo(new File(path));
            return path;
        }catch (IOException e){
            e.printStackTrace();
        }
        return "上传图片失败!";
    }

    @PostMapping("/upImg")
    public String upImg(MultipartFile file) throws IOException {
        return UploadUtil.uploadImage(file);
    }

}
